package v1

import (
	"gitee.com/buddyxiao/ginblog/model"
	"gitee.com/buddyxiao/ginblog/utils"
	"gitee.com/buddyxiao/ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// AddArticle 添加文章
func AddArticle(ctx *gin.Context) {
	var data model.Article
	_ = ctx.ShouldBindJSON(&data)
	code := model.CreateArticle(&data)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// GetArticles 查询文章列表
func GetArticles(ctx *gin.Context) {
	pageNum, _ := strconv.Atoi(ctx.Query("pageNum"))
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	title := ctx.Query("title")
	// 页码预处理
	utils.CheckPage(&pageNum, &pageSize)
	data, code, total := model.GetArticles(title, pageNum, pageSize)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"total":  total,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// GetAllArticleOnCategory 查询分类下的文章
func GetAllArticleOnCategory(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	pageNum, _ := strconv.Atoi(ctx.Query("pageNum"))
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	utils.CheckPage(&pageNum, &pageSize)
	data, code, total := model.GetAllArticleOnCategory(id, pageNum, pageSize)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"total":  total,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// GetArticle 查询谋篇文章
func GetArticle(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	article, code := model.GetArticle(id)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   article,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// EditArticle 编辑文章
func EditArticle(ctx *gin.Context) {
	var data model.Article
	id, _ := strconv.Atoi(ctx.Param("id"))
	_ = ctx.ShouldBindJSON(&data)
	code := model.EditArticle(id, &data)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// DeleteArticle 删除文章
func DeleteArticle(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	code := model.DeleteArticle(id)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})

}
